<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>英语单词点读机</title>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, "SF Pro Text", "SF Pro Icons", "Helvetica Neue", Arial, sans-serif;
            max-width: 1000px;
            margin: 0 auto;
            padding: 40px 20px;
            text-align: center;
            background-color: #ffffff;
            color: #1d1d1f;
        }

        #word-display {
            font-size: 56px;
            font-weight: 600;
            padding: 40px;
            margin: 40px auto;
            border-radius: 18px;
            cursor: pointer;
            background-color: #fbfbfd;
            min-height: 120px;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.3s ease;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }

        #word-display:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15);
        }

        #start-btn {
            font-size: 17px;
            font-weight: 400;
            padding: 12px 32px;
            margin: 20px;
            background-color: #0071e3;
            color: white;
            border: none;
            border-radius: 980px;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        #start-btn:hover {
            background-color: #0077ed;
            transform: scale(1.02);
        }

        #word-input {
            width: 100%;
            max-width: 600px;
            height: 150px;
            margin: 300px auto;
            padding: 16px;
            font-size: 17px;
            line-height: 1.5;
            border-radius: 14px;
            border: 1px solid #d2d2d7;
            background-color: #fbfbfd;
            transition: all 0.3s ease;
            resize: none;
            font-family: inherit;
        }

        #word-input:focus {
            outline: none;
            border-color: #0071e3;
            box-shadow: 0 0 0 4px rgba(0, 113, 227, 0.1);
        }

        @media (max-width: 734px) {
            body {
                padding: 20px;
            }

            #word-display {
                font-size: 40px;
                padding: 30px;
                margin: 30px auto;
            }
        }
    </style>
</head>
<body>
    <div id="word-display">点击开始</div>
    <div id="word-info" style="display: none; margin: 20px auto; max-width: 800px; text-align: left; background-color: #fbfbfd; padding: 20px; border-radius: 18px; box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);">
        <div id="word-meaning" style="font-size: 24px; margin-bottom: 15px;"></div>
        <div id="word-example" style="font-size: 18px; color: #666;"></div>
    </div>
    <div style="margin: 20px;">
        <button id="start-btn" style="font-size: 17px; font-weight: 400; padding: 12px 32px; margin: 10px; background-color: #0071e3; color: white; border: none; border-radius: 980px; cursor: pointer; transition: all 0.3s ease;">开始</button>
        <button id="favorite-btn" style="font-size: 17px; font-weight: 400; padding: 12px 32px; margin: 10px; background-color: #ff6b6b; color: white; border: none; border-radius: 980px; cursor: pointer; transition: all 0.3s ease;">收藏</button>
        <button id="dictation-btn" style="font-size: 17px; font-weight: 400; padding: 12px 32px; margin: 10px; background-color: #4CAF50; color: white; border: none; border-radius: 980px; cursor: pointer; transition: all 0.3s ease;">听写模式</button>
    </div>
    <div id="stats" style="margin: 20px auto; max-width: 600px; background-color: #fbfbfd; padding: 20px; border-radius: 18px; box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);">
        <h3 style="margin: 0 0 15px 0;">学习统计</h3>
        <div style="display: flex; justify-content: space-around; text-align: center;">
            <div>
                <div style="font-size: 24px; font-weight: bold;" id="total-words">0</div>
                <div>总单词数</div>
            </div>
            <div>
                <div style="font-size: 24px; font-weight: bold;" id="learned-words">0</div>
                <div>已学习</div>
            </div>
            <div>
                <div style="font-size: 24px; font-weight: bold;" id="favorite-words">0</div>
                <div>收藏单词</div>
            </div>
        </div>
    </div>
    <input type="file" id="file-input" accept=".xlsx,.txt" style="display: none;">
    <button id="import-btn" style="font-size: 17px; font-weight: 400; padding: 12px 32px; margin: 20px; background-color: #0071e3; color: white; border: none; border-radius: 980px; cursor: pointer; transition: all 0.3s ease;">导入单词</button>
    <br>
    <textarea id="word-input" placeholder="请输入单词，每行一个">hello
world
apple
banana
orange
book
computer
phone
table
chair</textarea>

    <script src="xlsx.full.min.js"></script>
    <script>
        const wordDisplay = document.getElementById('word-display');
        const startBtn = document.getElementById('start-btn');
        const wordInput = document.getElementById('word-input');
        const fileInput = document.getElementById('file-input');
        const importBtn = document.getElementById('import-btn');
        const favoriteBtn = document.getElementById('favorite-btn');
        const dictationBtn = document.getElementById('dictation-btn');
        const wordInfo = document.getElementById('word-info');
        const wordMeaning = document.getElementById('word-meaning');
        const wordExample = document.getElementById('word-example');
        const totalWordsEl = document.getElementById('total-words');
        const learnedWordsEl = document.getElementById('learned-words');
        const favoriteWordsEl = document.getElementById('favorite-words');
        
        let words = [];
        let currentWord = '';
        let isRotating = false;
        let isDictationMode = false;
        let learnedWords = new Set();
        let favoriteWords = new Set();
        let currentIndex = 0; // 添加当前单词索引
        
        // 从localStorage加载数据
        function loadStorageData() {
            const storedLearnedWords = localStorage.getItem('learnedWords');
            const storedFavoriteWords = localStorage.getItem('favoriteWords');
            if (storedLearnedWords) learnedWords = new Set(JSON.parse(storedLearnedWords));
            if (storedFavoriteWords) favoriteWords = new Set(JSON.parse(storedFavoriteWords));
            updateStats();
        }
        
        // 更新统计数据
        function updateStats() {
            totalWordsEl.textContent = words.length;
            learnedWordsEl.textContent = learnedWords.size;
            favoriteWordsEl.textContent = favoriteWords.size;
        }

        // 导入按钮点击事件
        importBtn.addEventListener('click', () => {
            fileInput.click();
        });

        // 文件选择事件
        fileInput.addEventListener('change', async (e) => {
            const file = e.target.files[0];
            if (!file) return;

            try {
                if (file.name.endsWith('.xlsx')) {
                    // 处理Excel文件
                    const data = await file.arrayBuffer();
                    const workbook = XLSX.read(data);
                    const worksheet = workbook.Sheets[workbook.SheetNames[0]];
                    const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
                    const words = jsonData.flat().filter(word => word && typeof word === 'string');
                    wordInput.value = words.join('\n');
                } else if (file.name.endsWith('.txt')) {
                    // 处理文本文件
                    const text = await file.text();
                    wordInput.value = text;
                }
                initWords();
                loadStorageData();
            } catch (error) {
                console.error('Error importing file:', error);
                alert('导入文件时出错，请确保文件格式正确');
            }

            // 清除文件选择，允许重复选择同一个文件
            fileInput.value = '';
        });


        // 初始化单词列表
        function initWords() {
            words = wordInput.value.split('\n').filter(word => word.trim() !== '');
        }

        // 获取随机单词
        function getRandomWord() {
            return words[Math.floor(Math.random() * words.length)];
        }

        // 播放单词发音并显示释义
        async function playWordAudio(word) {
            try {
                const response = await fetch(`https://api.dictionaryapi.dev/api/v2/entries/en/${word}`);
                const data = await response.json();
                
                if (data && data[0]) {
                    // 播放发音
                    if (data[0].phonetics && data[0].phonetics.length > 0) {
                        const audioUrl = `http://dict.youdao.com/dictvoice?type=1&audio=${word}`
                        if (audioUrl) {
                            const audio = new Audio(audioUrl);
                            audio.play();
                        }
                    }
                    
                    // 显示释义和例句
                    if (!isDictationMode) {
                        const meaning = data[0].meanings[0]?.definitions[0]?.definition || '无释义';
                        const example = data[0].meanings[0]?.definitions[0]?.example || '无例句';
                        wordMeaning.textContent = `释义：${meaning}`;
                        wordExample.textContent = `例句：${example}`;
                        wordInfo.style.display = 'block';
                    }
                    
                    // 标记为已学习
                    learnedWords.add(word);
                    localStorage.setItem('learnedWords', JSON.stringify([...learnedWords]));
                    updateStats();
                }
            } catch (error) {
                console.error('Error fetching audio:', error);
            }
        }

        // 轮播显示单词
        function rotateWords() {
            if (isRotating) return;
            isRotating = true;
            
            // 随机打乱单词数组
            const shuffledWords = [...words].sort(() => Math.random() - 0.5);
            
            let index = 0;
            const duration = 3000; // 3秒
            const interval = duration / shuffledWords.length;
            
            const rotation = setInterval(() => {
                if (index >= shuffledWords.length) {
                    clearInterval(rotation);
                    isRotating = false;
                    currentWord = shuffledWords[shuffledWords.length - 1];
                    return;
                }
                currentWord = shuffledWords[index];
                wordDisplay.textContent = currentWord;
                index++;
            }, interval);
        }

        // 点击单词显示区播放发音
        wordDisplay.addEventListener('click', () => {
            if (currentWord && !isRotating) {
                playWordAudio(currentWord);
            }
        });

        // 点击开始按钮显示随机单词
        startBtn.addEventListener('click', () => {
            initWords();
            if (isDictationMode) {
                // 听写模式下顺序显示单词
                if (currentIndex >= words.length) {
                    currentIndex = 0; // 重置索引
                }
                currentWord = words[currentIndex];
                wordDisplay.textContent = '点击播放发音';
                playWordAudio(currentWord);
                currentIndex++;
            } else {
                rotateWords();
            }
        });

        // 收藏按钮点击事件
        favoriteBtn.addEventListener('click', () => {
            if (currentWord && !isRotating) {
                if (favoriteWords.has(currentWord)) {
                    favoriteWords.delete(currentWord);
                    favoriteBtn.style.backgroundColor = '#ff6b6b';
                } else {
                    favoriteWords.add(currentWord);
                    favoriteBtn.style.backgroundColor = '#ffd93d';
                }
                localStorage.setItem('favoriteWords', JSON.stringify([...favoriteWords]));
                updateStats();
            }
        });
        
        // 听写模式切换
        dictationBtn.addEventListener('click', () => {
            isDictationMode = !isDictationMode;
            currentIndex = 0; // 重置索引
            if (isDictationMode) {
                dictationBtn.style.backgroundColor = '#ff6b6b';
                wordDisplay.textContent = '点击播放发音';
                wordInfo.style.display = 'none';
                startBtn.textContent = '下一个'; // 更改按钮文本
            } else {
                dictationBtn.style.backgroundColor = '#4CAF50';
                wordDisplay.textContent = currentWord || '点击开始';
                if (currentWord) wordInfo.style.display = 'block';
                startBtn.textContent = '开始'; // 恢复按钮文本
            }
        });
        
        // 初始化
        initWords();
        loadStorageData();
    </script>
</body>
</html>